package protocol;

import java.util.Iterator;
import java.util.LinkedList;

public class XmlBuilder {

	public String tag, value;
	public LinkedList<XmlBuilder> children;

	public XmlBuilder(String tag) {
		this.tag = tag;
	}

	public XmlBuilder setValue(String value) {
		this.children = null;
		this.value = value;
		return this;
	}

	public XmlBuilder addChildren(XmlBuilder child) {
		value = null;
		if(children == null)
			children = new LinkedList<XmlBuilder>();
		children.add(child);
		return this;
	}

	protected void generateChildrenBasedValue() {
		value = "";
		if(children != null) {
			Iterator<XmlBuilder> it = children.iterator();
			while(it.hasNext()) {
				value += it.next().toString();
			}
		}
	}

	public void recursiverResetOfToStrig() {
		if(children != null) {
			value = null;
			Iterator<XmlBuilder> it = children.iterator();
			while(it.hasNext()) {
				it.next().recursiverResetOfToStrig();
			}
		}
	}
	
	@Override
	public String toString() {
		if(value == null)
			generateChildrenBasedValue();
		return "<"+tag+">"+value+"</"+tag+">";
	}

}
